import React, { useEffect, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Form, Typography, Row, Col, Input, Slider, Button, InputNumber } from 'antd';
import { createGlobalStyle } from 'styled-components';
import type { RootState } from '@/store';
import { selectAudioById, updateAudio } from '@/store/audiosSlice';
import type { Audio } from '@/store/audiosSlice';

const { Title, Text } = Typography;

interface FormValues {
    audioName: string;
    speed: number;
    volume: number;
    fadeInDuration: number;
    fadeOutDuration: number;
    target_timerange_start: number;
    target_timerange_duration: number;
    source_timerange_start: number;
    source_timerange_duration: number;
}

interface ConfigAudioFormProps {
    audioId: string;
}

// 定义全局 Ant Design 深色主题样式
const GlobalAntdDarkThemeStyle = createGlobalStyle`
    /* 自定义滚动条样式 */
    .config-audio-form-scroll::-webkit-scrollbar {
        width: 3px;
        background: transparent;
    }
    .config-audio-form-scroll::-webkit-scrollbar-thumb {
        background: #715BB8; /* 滚动条颜色，可根据需要调整 */
        border-radius: 4px;
    }

    /* Ant Design 表单标签颜色 */
    .ant-form-item-label > label {
        color: #FFFFFF !important; /* 所有标签文本设为白色 */
    }

    /* 输入框 (Input, InputNumber) 和选择框 (Select) 的基础样式 */
    .ant-input,
    .ant-input-number-input,
    .ant-select-selector {
        background-color: #3C3C3C !important; /* 输入框背景色 */
        color: #FFFFFF !important; /* 输入框文本颜色 */
        border-color: #555555 !important; /* 输入框边框颜色 */
    }

    /* 输入框和选择框的悬停/聚焦状态 */
    .ant-input:hover,
    .ant-input-number:hover .ant-input-number-input,
    .ant-select:not(.ant-select-disabled):hover .ant-select-selector {
        border-color: #888888 !important; /* 悬停时边框颜色 */
    }
    .ant-input:focus,
    .ant-input-focused,
    .ant-input-number-focused .ant-input-number-input,
    .ant-select-focused:not(.ant-select-disabled) .ant-select-selector {
        box-shadow: 0 0 0 2px rgba(136, 136, 136, 0.2) !important; /* 聚焦时阴影 */
        border-color: #888888 !important; /* 聚焦时边框颜色 */
    }

    /* Slider 组件样式 */
    .ant-slider-rail {
        background-color: #555555 !important; /* 轨道背景色 */
    }
    .ant-slider-track {
        background-color: #715BB8 !important; /* 已选择部分轨道颜色 */
    }
    .ant-slider-handle {
        border-color: #715BB8 !important; /* 滑块边框颜色 */
        background-color: #FFFFFF !important; /* 滑块背景色 */
    }
    .ant-slider-handle:hover,
    .ant-slider-handle:focus {
        border-color: #715BB8 !important; /* 悬停/聚焦时滑块边框颜色 */
        box-shadow: 0 0 0 5px rgba(113, 91, 184, 0.2) !important; /* 聚焦时阴影 */
    }
    .ant-slider-mark-text {
        color: #FFFFFF !important; /* 刻度文本颜色 */
    }
    /* 提示框样式 */
    .ant-tooltip-inner {
        background-color: #3C3C3C !important; /* 提示框背景色 */
        border-color: #555555 !important; /* 提示框边框颜色 */
        color: #FFFFFF !important; /* 提示框文本颜色 */
    }
`;

// 计算速度变化时的持续时间
const calculateDuration = (originalDuration: number, originalSpeed: number, newSpeed: number) => {
    return Math.round(((originalDuration * originalSpeed) / newSpeed) * 100) / 100;
};

const ConfigAudioForm: React.FC<ConfigAudioFormProps> = ({ audioId }) => {
    const [form] = Form.useForm<FormValues>();
    const dispatch = useDispatch();

    // 根据ID获取音频配置 - 确保audioId是string类型
    const audio = useSelector((state: RootState) => (audioId ? selectAudioById(state, String(audioId)) : null));
    const trackItem = useSelector((state: RootState) => (audioId ? state.tracks.tracks.flatMap((track) => track.items).find((item) => item.type === 'audio' && item.id === String(audioId)) : null));

    // 处理表单值变化，更新Redux
    const handleValuesChange = useCallback(
        (changedValues: any, allValues: FormValues) => {
            if (!audioId || !audio) return;

            // 重新构建要更新的 config 对象
            const updates: Partial<Audio> = {};

            // 检查每个可能变化的字段
            if ('audioName' in changedValues) updates.name = allValues.audioName;
            if ('speed' in changedValues) {
                // 计算新的持续时间
                const currentAudioDuration = audio.target_timerange[1];
                const currentAudioSpeed = audio.speed;
                const newDuration = calculateDuration(currentAudioDuration, currentAudioSpeed, allValues.speed);
                updates.speed = allValues.speed;
                updates.target_timerange = [audio.target_timerange[0], newDuration];
            }
            if ('volume' in changedValues) updates.volume = allValues.volume;
            if ('fadeInDuration' in changedValues || 'fadeOutDuration' in changedValues) {
                const fadeInDuration = allValues.fadeInDuration || parseFloat(audio.fade.in_duration);
                const fadeOutDuration = allValues.fadeOutDuration || parseFloat(audio.fade.out_duration);
                updates.fade = {
                    in_duration: `${fadeInDuration}s`,
                    out_duration: `${fadeOutDuration}s`,
                };
            }
            // 处理时间范围字段
            if ('target_timerange_start' in changedValues || 'target_timerange_duration' in changedValues) {
                updates.target_timerange = [allValues.target_timerange_start, allValues.target_timerange_duration];
            }
            if ('source_timerange_start' in changedValues || 'source_timerange_duration' in changedValues) {
                updates.source_timerange = [allValues.source_timerange_start, allValues.source_timerange_duration];
            }

            if (Object.keys(updates).length > 0) {
                dispatch(
                    updateAudio({
                        id: String(audioId),
                        updates: { ...audio, ...updates },
                    })
                );
            }
        },
        [audioId, audio, dispatch]
    );

    // 在组件加载或 audio 变化时设置表单值
    useEffect(() => {
        if (audio) {
            // 解析fade时间（移除's'后缀）
            const fadeInDuration = parseFloat(audio.fade.in_duration);
            const fadeOutDuration = parseFloat(audio.fade.out_duration);

            // 确保音频名称有值
            const audioName = audio.name || '未命名音频';

            // 设置表单值
            const formValues: FormValues = {
                audioName: audioName,
                speed: audio.speed,
                volume: audio.volume,
                fadeInDuration: fadeInDuration,
                fadeOutDuration: fadeOutDuration,
                target_timerange_start: audio.target_timerange[0],
                target_timerange_duration: audio.target_timerange[1],
                source_timerange_start: audio.source_timerange[0],
                source_timerange_duration: audio.source_timerange[1],
            };

            form.setFieldsValue(formValues);
        } else {
            // 没有音频数据时，清空表单
            form.resetFields();
        }
    }, [audio, form, audioId]); // 依赖 audio, form, audioId

    if (!audioId) {
        return (
            <div
                style={{
                    padding: '20px',
                    color: '#FFFFFF',
                    backgroundColor: '#282828',
                    height: '100%',
                }}
            >
                未选择任何音频片段
            </div>
        );
    }

    return (
        <>
            <GlobalAntdDarkThemeStyle /> {/* 应用全局深色主题样式 */}
            <div
                style={{
                    maxHeight: 540,
                    overflowX: 'hidden',
                    overflowY: 'auto',
                    backgroundColor: '#282828',
                    color: '#FFFFFF',
                    padding: '16px',
                    borderRadius: '8px',
                }}
                className="config-audio-form-scroll"
            >
                <Title level={4} style={{ marginBottom: 16, color: '#FFFFFF' }}>
                    属性面板
                </Title>
                <Title level={5} style={{ marginTop: 0, marginBottom: 8, color: '#FFFFFF' }}>
                    当前选择
                </Title>

                {/* 显示当前选择的音频信息 */}
                {audio && (
                    <div
                        style={{
                            backgroundColor: '#3C3C3C',
                            color: '#FFFFFF',
                            padding: '8px 12px',
                            borderRadius: '4px',
                            marginBottom: '16px',
                            border: '1px solid #555555',
                        }}
                    >
                        <Typography.Text style={{ color: '#FFFFFF' }}>
                            <i className="icon-audio">🔊</i> {audio.name || '未命名音频'}
                        </Typography.Text>
                    </div>
                )}

                <Form form={form} layout="vertical" onValuesChange={handleValuesChange}>
                    {/* 音频名称 */}
                    <Form.Item label="音频名称" name="audioName" rules={[{ required: true, message: '请输入音频名称' }]}>
                        <Input style={{ width: '98%' }} />
                    </Form.Item>

                    {/* 播放设置 */}
                    <Title
                        level={5}
                        style={{
                            marginTop: 16,
                            marginBottom: 8,
                            color: '#FFFFFF',
                        }}
                    >
                        播放设置
                    </Title>
                    <Row gutter={24}>
                        <Col span={12}>
                            <Form.Item
                                label="播放速度"
                                name="speed"
                                rules={[
                                    {
                                        required: true,
                                        message: '请设置播放速度',
                                    },
                                ]}
                                style={{ marginBottom: '24px' }}
                            >
                                <Slider
                                    min={0.1}
                                    max={3}
                                    step={0.1}
                                    marks={{
                                        0.1: '0.1x',
                                        1: '1x',
                                        2: '2x',
                                        3: '3x',
                                    }}
                                    tooltip={{
                                        formatter: (value) => `${value}x`,
                                    }}
                                    style={{ width: '80%' }}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="音量" name="volume" rules={[{ required: true, message: '请设置音量' }]} style={{ marginBottom: '24px' }}>
                                <Slider
                                    min={0}
                                    max={1}
                                    step={0.01}
                                    marks={{
                                        0: '0%',
                                        0.5: '50%',
                                        1: '100%',
                                    }}
                                    tooltip={{
                                        formatter: (value) => (value !== undefined ? `${Math.round(value * 100)}%` : ''),
                                    }}
                                    style={{ width: '80%' }}
                                />
                            </Form.Item>
                        </Col>
                    </Row>

                    {/* 时间范围设置 */}
                    <Title
                        level={5}
                        style={{
                            marginTop: 16,
                            marginBottom: 8,
                            color: '#FFFFFF',
                        }}
                    >
                        时间范围设置
                    </Title>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="目标开始 (秒)" name="target_timerange_start">
                                <InputNumber min={0} step={0.1} precision={2} style={{ width: '90%' }} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="目标持续 (秒)" name="target_timerange_duration">
                                <InputNumber min={0} step={0.1} precision={2} style={{ width: '90%' }} />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="源开始 (秒)" name="source_timerange_start">
                                <InputNumber min={0} step={0.1} precision={2} style={{ width: '90%' }} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="源持续 (秒)" name="source_timerange_duration">
                                <InputNumber min={0} step={0.1} precision={2} style={{ width: '90%' }} />
                            </Form.Item>
                        </Col>
                    </Row>

                    {/* 淡入淡出效果 */}
                    <Title
                        level={5}
                        style={{
                            marginTop: 16,
                            marginBottom: 8,
                            color: '#FFFFFF',
                        }}
                    >
                        淡入淡出效果
                    </Title>
                    <Row gutter={24}>
                        <Col span={12}>
                            <Form.Item
                                label="淡入持续时间(s)"
                                name="fadeInDuration"
                                rules={[
                                    {
                                        required: true,
                                        message: '请设置淡入时间',
                                    },
                                ]}
                                style={{ marginBottom: '24px' }}
                            >
                                <Slider
                                    min={0}
                                    max={5}
                                    step={0.1}
                                    marks={{
                                        0: '0s',
                                        2.5: '2.5s',
                                        5: '5s',
                                    }}
                                    tooltip={{
                                        formatter: (value) => `${value}s`,
                                    }}
                                    style={{ width: '80%' }}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                label="淡出持续时间(s)"
                                name="fadeOutDuration"
                                rules={[
                                    {
                                        required: true,
                                        message: '请设置淡出时间',
                                    },
                                ]}
                                style={{ marginBottom: '24px' }}
                            >
                                <Slider
                                    min={0}
                                    max={5}
                                    step={0.1}
                                    marks={{
                                        0: '0s',
                                        2.5: '2.5s',
                                        5: '5s',
                                    }}
                                    tooltip={{
                                        formatter: (value) => `${value}s`,
                                    }}
                                    style={{ width: '80%' }}
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>
        </>
    );
};
export default ConfigAudioForm;
